/**
* All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
*
* SdProjectHistoryService
* SD项目立项-历史表
*
* 修改纪录
* 2021-12-06 版本：1.0 wangxinhua 创建。
* @version 版本：1.0
* @author 作者：wangxinhua
* 创建日期：2021-12-06
*/
package com.topscomm.gpm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.topscomm.base.BaseSystemConst;
import com.topscomm.base.pojo.BaseChangeLogEntity;
import com.topscomm.base.service.impl.BaseChangeLogService;
import com.topscomm.base.service.impl.BasePropertyService;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.ltc.service.ILtcContractProductInfoService;
import com.topscomm.mms.service.impl.MmsDeptExtraInfoService;
import com.topscomm.pub.util.*;
import com.topscomm.gpm.GpmSystemConst;
import com.topscomm.gpm.pojo.*;
import com.topscomm.gpm.service.IGpmProjectHistoryService;
import com.topscomm.gpm.service.impl.auto.GpmProjectHistoryServiceAuto;
import com.topscomm.tap.common.TapSystemConst;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service(value = "gpmProjectHistoryService")
@Scope(value = "singleton")
public class GpmProjectHistoryService extends GpmProjectHistoryServiceAuto implements IGpmProjectHistoryService {
    @Autowired
    private GpmWfFormService gpmWfFormService;
    @Autowired
    private GpmProjectService gpmProjectService;
    @Autowired
    private BaseChangeLogService baseChangeLogService;
    @Autowired
    private GpmProjectUniversalChangeService gpmProjectUniversalChangeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> doSave(Map<String, Object> inputMap) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> basicInfo = (Map<String, Object>) inputMap.get("basicInfo");
        GpmProjectHistoryEntity sdProjectEntity = new GpmProjectHistoryEntity();
        long id = 0L;
        if(basicInfo == null) {
            return resultMap;
        }
        sdProjectEntity.convertFromMap(basicInfo);
        sdProjectEntity = this.saveProjectInfo(sdProjectEntity);
        resultMap.put("id", sdProjectEntity.getId());
        return resultMap;
    }


    private void insertUniversalChange(GpmProjectHistoryEntity projectHistoryEntity) {
        GpmProjectUniversalChangeEntity universalChangeEntity = new GpmProjectUniversalChangeEntity();
        universalChangeEntity.setProjectname(projectHistoryEntity.getProjectname());
        universalChangeEntity.setProjectid(projectHistoryEntity.getProjectid());
        universalChangeEntity.setProjectcode(projectHistoryEntity.getProjectcode());
        universalChangeEntity.setSourcetype(GpmProjectHistoryEntity.tableName);
        universalChangeEntity.setSourceid(projectHistoryEntity.getId());
        universalChangeEntity.setProjectmanager(projectHistoryEntity.getProjectmanager());
        universalChangeEntity.setProjectmanagercode(projectHistoryEntity.getProjectmanagercode());
        universalChangeEntity.setChangereason(projectHistoryEntity.getChangereason());
        universalChangeEntity.setDeptname(getSessionUserBean().getDept().getFullname());
        universalChangeEntity.setDeptcode(getSessionUserBean().getDept().getCode());
        universalChangeEntity.setUsername(getSessionUserBean().getUser().getName());
        universalChangeEntity.setUsercode(getSessionUserBean().getUser().getCode());
        universalChangeEntity.setDocdate(new Date());
        universalChangeEntity.setVersion(projectHistoryEntity.getVersion());

        gpmProjectUniversalChangeService.insert(universalChangeEntity);
    }

    /***
     * @description: 新增或更新主表信息
     * @param sdProjectEntity
     * @return
     * @author: jiangtao1
     * @date: 2021/11/24 15:58
     * @modify:
     */
    private GpmProjectHistoryEntity saveProjectInfo(GpmProjectHistoryEntity sdProjectEntity) {
        long id = sdProjectEntity.getId();
        if (id <= 0) {
            long[] arrayId = PrimaryKeyUtil.GeneIDs(sdProjectEntity.getTableName(), 1);
            id = arrayId[0];
            sdProjectEntity.setId(id);
            sdProjectEntity.setState(0);
            long version = ConvertUtil.convertToLong(sdProjectEntity.getVersion());
            sdProjectEntity.setVersion(version + 1);
            this.insert(sdProjectEntity);
            //变更表模块生成一条记录
            this.insertUniversalChange(sdProjectEntity);
        } else {
            this.updateEntity(sdProjectEntity);
            //更新变更模块的变更原因字段
            Map<String,Object> changeUpdateMap = new HashMap<String,Object>();
            changeUpdateMap.put(GpmProjectUniversalChangeEntity.FieldChangereason, sdProjectEntity.getChangereason());
            gpmProjectUniversalChangeService.updateByWhere(changeUpdateMap,"sourceid="+sdProjectEntity.getId() + " and sourcetype='"+ GpmProjectHistoryEntity.tableName +"' and version="
                    +sdProjectEntity.getVersion());
        }
        return sdProjectEntity;
    }

	public Map<String, Object> getBaseChangeEntity(Map<String, Object> inputMap) throws Exception {
		long projectId = ConvertUtil.convertToLong(inputMap.get("projectid"));
        // 来源信息表
        List<Map<String, Object>> productSourceInfo = (List<Map<String, Object>>) inputMap.get("productSourceInfo");
        List<Map<String,Object>> customerInfo = (List<Map<String,Object>>) inputMap.get("customerInfo");
		// 获取之前版本主表数据
		Map<String, Object> historyData = gpmProjectService.queryMapByWhere(" id=" + projectId).get(0);
		// 所有变更数据返回
		Map<String, Object> resMap = new HashMap<String, Object>();
		// 组装主表要去对比的数据
		Map<String, Object> changeMap = new HashMap<String, Object>();
		changeMap.put("topsourcetype", GpmProjectHistoryEntity.tableName);
		changeMap.put("topsourceid", ConvertUtil.convertToString(inputMap.get("id")));
		changeMap.put("sourcetype", GpmProjectHistoryEntity.tableName);
		changeMap.put("sourceid", ConvertUtil.convertToString(inputMap.get("id")));
		changeMap.put("newmap", inputMap);
		changeMap.put("oldmap", historyData);
		changeMap.put("baselogoperatetype", BaseSystemConst.BaseLogOperateTypeEnum.Edit);
		changeMap.put("version", ConvertUtil.convertToString(inputMap.get("version")));
		BaseChangeLogEntity mainContent = this.getMainChangeLogEntity(changeMap);
		resMap.put("mainContent", mainContent);
		return resMap;
	}

	/**
	 * @description: 保存字段变更
	 * @param changeData
	 * @return void
	 * @author: wangxinhua
	 * @date: 2021/12/10 16:11
	 * @modify:
	 */
    public void saveBaseChangelog(Map<String, Object> changeData, Boolean ignoreNoChange) {
        BasicEntity mainContent = (BasicEntity)changeData.get("mainContent");
        if(mainContent == null && !ignoreNoChange){
            throw new ServiceException("无变更内容无法提交审批，请先更改数据！");
        }
        if(mainContent != null){
            baseChangeLogService.insert(mainContent);
        }
    }

    /***
     * @description: 立项申请提交审批
     * @param paraMap
     * @return
     * @author: wxh
     * @date: 2021/11/30 10:23
     * @modify:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doProjectChangeApproval(Map<String, Object> paraMap) {
        String id = ConvertUtil.convertToString(paraMap.get("id"));
        GpmProjectHistoryEntity projectHistoryEntity = this.queryById(id);
        int state = projectHistoryEntity.getState();
        if (TapSystemConst.TapApprovalNodeStateEnum.Approveing == state) {
            throw new ServiceException("该项目处于立项审核中，不允许重复提交审批");
        }
        // 查询变更项目是否为流程项目，如果是，执行流程项目变更
        GpmProjectEntity gpmProjectEntity = gpmProjectService.queryById(ConvertUtil.convertToString(projectHistoryEntity.getProjectid()));

        // 生成提交实体
        GpmWfFormEntity gpmWfFormEntity = new GpmWfFormEntity();
        long flowid = 0L;
        if (GpmSystemConst.GPM_APPROVAL_PROJECT_TYPE.GpmProcessProject.equals(gpmProjectEntity.getApprovalprojecttype())) {
            gpmWfFormEntity = gpmWfFormService.generateWfFormEntity(GpmProjectHistoryEntity.tableName,projectHistoryEntity, GpmSystemConst.SdApprovalCategory.SdProjectChange);
            flowid = gpmWfFormService.queryFlowid(GpmSystemConst.SdApprovalType.GpmProcessProjectChangeType, GpmSystemConst.SdApprovalCode.GpmProcessProjectChangeApproval,this.getSessionUserBean());
        } else { // 通用管理项目变更
            gpmWfFormEntity = gpmWfFormService.generateWfFormEntity(GpmProjectHistoryEntity.tableName,projectHistoryEntity, GpmSystemConst.SdApprovalCategory.SdProjectChange);
            flowid = gpmWfFormService.queryFlowid(GpmSystemConst.SdApprovalType.SdProjectChangeType, GpmSystemConst.SdApprovalCode.ProjectChangeApproval,this.getSessionUserBean());
        }
        if (flowid <= 0) {
            throw new ServiceException("未找到对应的审批流程，请联系管理员");
        }
        gpmWfFormEntity.setFlowid(flowid);
        gpmWfFormService.insert(gpmWfFormEntity);
        StringBufferProxy mailtitle = new StringBufferProxy();
        String flowname = "";
        if (GpmSystemConst.GPM_APPROVAL_PROJECT_TYPE.GpmProcessProject.equals(gpmProjectEntity.getApprovalprojecttype())) {
            flowname = "流程项目立项变更";
        } else { // 通用管理项目变更
            flowname = "项目立项变更";
        }
        mailtitle.appendSingle("{0}{1}于{2}提交{3}审批流程,单据编号{4}! ", this.getSessionUserBean().getDept().getFullname(),
                gpmWfFormEntity.getUsername(), com.topscomm.pub.util.DateUtil.dateToString(new Date(), "yyyy-MM-dd"),
                flowname, gpmWfFormEntity.getDocno());
        // 审批提交
        gpmWfFormService.executeSubmit(gpmWfFormEntity, mailtitle.toString(), this.getSessionUserBean());
        // 提交审批后操作saveBaseChangeLog
        this.afterProjectChangeApproval(projectHistoryEntity);
        //修改变更模块记录
        Map<String,Object> changeUpdateMap = new HashMap<String,Object>();
        changeUpdateMap.put(GpmProjectUniversalChangeEntity.FieldState, 1);
        changeUpdateMap.put(GpmProjectUniversalChangeEntity.FieldLatestphase, gpmWfFormEntity.getLatestphase());
        changeUpdateMap.put(GpmProjectUniversalChangeEntity.FieldSubmitdate, new Date());
        gpmProjectUniversalChangeService.updateByWhere(changeUpdateMap,"sourceid="+ gpmWfFormEntity.getSourceid() + " and sourcetype='"+ GpmProjectHistoryEntity.tableName +"' and version="
                + gpmWfFormEntity.getVersion());
    }

    private void afterProjectChangeApproval(GpmProjectHistoryEntity projectHistoryEntity) {
        //更新历史state
        projectHistoryEntity.setState(1);
        this.updateEntity(projectHistoryEntity);
        Map<String, Object> nowHistoryInfo = projectHistoryEntity.convertToMap();
        try {
            //删除上次德basechangelog
            baseChangeLogService.deleteByWhere(" topsourcetype='"+projectHistoryEntity.getTableName()+"'"
                    + " and topsourceid='"+projectHistoryEntity.getId()+"'"
                    + " and version="+projectHistoryEntity.getVersion());
            Map<String, Object> changeData = getBaseChangeEntity(nowHistoryInfo);
            saveBaseChangelog(changeData, false);
        }catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }


    /**
     * @author: wudaliang
     * @date: 2021-07-16
     * @param: projectcode2
     * @param: mpmProjectChangeEntity
     * @description: 立项变更审批完后
     * @return: void
     * @modify:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void projectChangeUpdate(String projectcode, GpmProjectHistoryEntity gpmProjectHistoryEntity) throws Exception {
        gpmProjectHistoryEntity.setState(9);
        GpmProjectEntity gpmProjectEntity = new GpmProjectEntity();
        GpmProjectEntity tempEntity = gpmProjectService.queryById(ConvertUtil.convertToString(gpmProjectHistoryEntity.getProjectid()));
        String whetherhistorydata = "";
        String approvalprojecttype = "";
        if(tempEntity!=null) {
            whetherhistorydata = tempEntity.getWhetherhistorydata();
            approvalprojecttype = tempEntity.getApprovalprojecttype();
        }
        BeanUtils.copyProperties(gpmProjectHistoryEntity, gpmProjectEntity);
        gpmProjectEntity.setId(gpmProjectHistoryEntity.getProjectid());
        gpmProjectEntity.setProjectstate(ConvertUtil.convertToString(gpmProjectHistoryEntity.getProjectstate()));
        Map<Long,Long> sourceIdMap = new HashMap<Long,Long>();
        //更新项目历史状态
        this.updateEntity(gpmProjectHistoryEntity);
        //更新项目主表
        gpmProjectEntity.setWhetherhistorydata(whetherhistorydata);
        gpmProjectEntity.setApprovalprojecttype(approvalprojecttype);
        gpmProjectService.updateEntity(gpmProjectEntity);
    }


    public void updateLevelHistory(Map<String,Object> paraMap){
        String oldprojectlevel = paraMap.get("oldprojectlevel").toString();
        String newprojectlevel = paraMap.get("newprojectlevel").toString();
        if (StringUtil.isEmpty(oldprojectlevel) || StringUtil.isEmpty(newprojectlevel)) {
            return;
        }
        int oldlevel = Integer.parseInt(oldprojectlevel);
        int newlevel = Integer.parseInt(newprojectlevel);
        JSONObject record = new JSONObject();
        String[] levelArray={"A","B","C","D"};
        record.put("oldprojectlevel",levelArray[oldlevel]);
        record.put("newprojectlevel",levelArray[newlevel]);
        //更新项目等级变更历史字段
        HashMap<String, Object> updateMap = new HashMap<>();
        if(paraMap.containsKey("ismobile")){
            //获取wfform表数据
            GpmWfFormEntity gpmWfFormEntity = gpmWfFormService.queryById(ConvertUtil.convertToString(paraMap.get("id")));
            updateMap.put("id", ConvertUtil.convertToString(gpmWfFormEntity.getSourceid()));
        } else {
            updateMap.put("id",paraMap.get("id"));
        }
        updateMap.put("levelhistory",record.toString());
        this.update(updateMap);
    }
}
